package com.zhaopin.springboot.service.impl;

import com.zhaopin.springboot.mapper.StudentMapper;
import com.zhaopin.springboot.model.Student;
import com.zhaopin.springboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @create 2021-04-20 10:18
 */
@Service
public class StudentServiceImpl implements StudentService {


    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public Student getStudentById(Integer id) {
        return studentMapper.selectByPrimaryKey(id);
    }

    @Transactional
    @Override
    public Integer updateByKey(Student student) {

        Integer i = studentMapper.updateByPrimaryKeySelective(student);
        //此处会抛出异常 根据事务的配置进行回滚，
        // int a = 3 / 0;
        return i;

    }

    @Override
    public Object allStudentCount() {

        redisTemplate.setKeySerializer(new StringRedisSerializer());

        Long allStudentCount = (Long)
                redisTemplate.opsForValue().get("allStudentCount");

        //redis做缓存
        if (null == allStudentCount) {
            allStudentCount = studentMapper.allStudentCount();
            redisTemplate.opsForValue().set("allStudentCount", allStudentCount, 30,
                    TimeUnit.SECONDS);

        }
        return allStudentCount;


    }
}
